package com.jch.protobuf.server;

import com.googlecode.protobuf.format.JsonFormat;
import com.jch.protobuf.domain.MsgBody;
import com.jch.protobuf.util.MsgUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.text.SimpleDateFormat;
import java.util.Date;

public class ServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端：" + ctx.channel().remoteAddress().toString() + " 接入。");
        String msgInfo = "服务端告知客户端连接成功。时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS").format(new Date());
        ctx.writeAndFlush(MsgUtil.buildMsg(ctx.channel().id().toString(), msgInfo));
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端主动断开连接：" + ctx.channel().remoteAddress().toString());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String dateStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS").format(new Date());
        System.out.println(dateStr + " 收到消息类型：" + msg.getClass());
//        System.out.println(dateStr + " 收到消息内容：" + ((MsgBody) msg).getMsgInfo());
        System.out.println(dateStr + " 收到消息内容：" + new JsonFormat().printToString((MsgBody) msg));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        System.out.println("异常信息：" + cause.getMessage());
    }
}
